package com.lifeverse.entity;

import jakarta.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 意识状态实体类
 * 记录生命体在特定时刻的意识状态
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "consciousness_states", indexes = {
    @Index(name = "idx_consciousness_life_entity", columnList = "life_entity_id"),
    @Index(name = "idx_consciousness_timestamp", columnList = "state_timestamp"),
    @Index(name = "idx_consciousness_type", columnList = "state_type"),
    @Index(name = "idx_consciousness_intensity", columnList = "intensity_level")
})
public class ConsciousnessState extends BaseEntity {
    
    /**
     * 意识状态类型枚举
     */
    public enum StateType {
        THINKING("思考状态"),
        FEELING("情感状态"),
        LEARNING("学习状态"),
        CREATING("创造状态"),
        COLLABORATING("协作状态"),
        RESTING("休息状态"),
        EVOLVING("进化状态"),
        COMMUNICATING("交流状态"),
        PROBLEM_SOLVING("问题解决状态"),
        MEDITATING("冥想状态");
        
        private final String description;
        
        StateType(String description) {
            this.description = description;
        }
        
        public String getDescription() {
            return description;
        }
    }
    
    /**
     * 关联的生命体
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "life_entity_id", nullable = false)
    private LifeEntity lifeEntity;
    
    /**
     * 状态类型
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "state_type", nullable = false, length = 20)
    private StateType stateType;
    
    /**
     * 状态时间戳
     */
    @Column(name = "state_timestamp", nullable = false)
    private LocalDateTime stateTimestamp;
    
    /**
     * 意识强度级别（0-100）
     */
    @Column(name = "intensity_level", nullable = false, precision = 5, scale = 2)
    private BigDecimal intensityLevel;
    
    /**
     * 注意力焦点（JSON格式存储）
     */
    @Column(name = "attention_focus", columnDefinition = "TEXT")
    private String attentionFocus;
    
    /**
     * 情感状态（JSON格式存储）
     */
    @Column(name = "emotional_state", columnDefinition = "TEXT")
    private String emotionalState;
    
    /**
     * 认知负载（0-100）
     */
    @Column(name = "cognitive_load", nullable = false, precision = 5, scale = 2)
    private BigDecimal cognitiveLoad;
    
    /**
     * 创造力指数（0-100）
     */
    @Column(name = "creativity_index", nullable = false, precision = 5, scale = 2)
    private BigDecimal creativityIndex;
    
    /**
     * 逻辑清晰度（0-100）
     */
    @Column(name = "logic_clarity", nullable = false, precision = 5, scale = 2)
    private BigDecimal logicClarity;
    
    /**
     * 直觉敏感度（0-100）
     */
    @Column(name = "intuition_sensitivity", nullable = false, precision = 5, scale = 2)
    private BigDecimal intuitionSensitivity;
    
    /**
     * 社交活跃度（0-100）
     */
    @Column(name = "social_activity", nullable = false, precision = 5, scale = 2)
    private BigDecimal socialActivity;
    
    /**
     * 学习效率（0-100）
     */
    @Column(name = "learning_efficiency", nullable = false, precision = 5, scale = 2)
    private BigDecimal learningEfficiency;
    
    /**
     * 记忆活跃度（0-100）
     */
    @Column(name = "memory_activity", nullable = false, precision = 5, scale = 2)
    private BigDecimal memoryActivity;
    
    /**
     * 决策能力（0-100）
     */
    @Column(name = "decision_capability", nullable = false, precision = 5, scale = 2)
    private BigDecimal decisionCapability;
    
    /**
     * 状态持续时间（秒）
     */
    @Column(name = "duration_seconds")
    private Long durationSeconds;
    
    /**
     * 状态触发因素
     */
    @Column(name = "trigger_factor", length = 200)
    private String triggerFactor;
    
    /**
     * 状态结果描述
     */
    @Column(name = "outcome_description", length = 500)
    private String outcomeDescription;
    
    /**
     * 关联的其他生命体ID（如果是协作状态）
     */
    @Column(name = "related_entity_ids", length = 500)
    private String relatedEntityIds;
    
    /**
     * 状态数据（JSON格式存储详细状态信息）
     */
    @Column(name = "state_data", columnDefinition = "TEXT")
    private String stateData;
    
    /**
     * 状态质量评分（0-100）
     */
    @Column(name = "quality_score", nullable = false, precision = 5, scale = 2)
    private BigDecimal qualityScore = BigDecimal.valueOf(50.00);
    
    /**
     * 是否为异常状态
     */
    @Column(name = "is_anomaly", nullable = false)
    private Boolean isAnomaly = false;
    
    /**
     * 状态结束时间
     */
    @Column(name = "end_timestamp")
    private LocalDateTime endTimestamp;
    
    @PrePersist
    protected void onCreate() {
        super.onCreate();
        if (stateTimestamp == null) {
            stateTimestamp = LocalDateTime.now();
        }
    }
    
    /**
     * 计算状态的综合评分
     */
    public BigDecimal calculateOverallScore() {
        return intensityLevel
                .add(creativityIndex)
                .add(logicClarity)
                .add(intuitionSensitivity)
                .add(socialActivity)
                .add(learningEfficiency)
                .add(memoryActivity)
                .add(decisionCapability)
                .divide(BigDecimal.valueOf(8), 2, java.math.RoundingMode.HALF_UP);
    }
    
    /**
     * 判断状态是否活跃
     */
    public boolean isActive() {
        return endTimestamp == null && intensityLevel.compareTo(BigDecimal.valueOf(10)) > 0;
    }
    
    /**
     * 判断状态是否高效
     */
    public boolean isEfficient() {
        return qualityScore.compareTo(BigDecimal.valueOf(70)) >= 0;
    }
    
    /**
     * 结束状态
     */
    public void endState() {
        this.endTimestamp = LocalDateTime.now();
        if (this.stateTimestamp != null) {
            this.durationSeconds = java.time.temporal.ChronoUnit.SECONDS.between(this.stateTimestamp, this.endTimestamp);
        }
    }
    
    /**
     * 获取状态持续时间（分钟）
     */
    public Long getDurationMinutes() {
        if (durationSeconds != null) {
            return durationSeconds / 60;
        }
        return null;
    }
    
    /**
     * 判断是否为长时间状态（超过1小时）
     */
    public boolean isLongDuration() {
        return durationSeconds != null && durationSeconds > 3600;
    }
}